import { onMounted, onActivated, onBeforeUnmount, onDeactivated, ref } from 'vue';
import { debounce } from 'hc-core/utils/index';

export default function useResize() {
    const $_sidebarElm = ref(null);
    const $_resizeHandler = ref(null);

    const resize = () => {
        const chart = getCurrentInstance()?.proxy?.chart;
        chart && chart.resize();
    };

    const $_sidebarResizeHandler = (e) => {
        if (e.propertyName === 'width') {
            $_resizeHandler.value && $_resizeHandler.value();
        }
    };

    const initListener = () => {
        $_resizeHandler.value = debounce(() => {
            resize();
        }, 100);
        window.addEventListener('resize', $_resizeHandler.value);

        $_sidebarElm.value = document.getElementsByClassName('sidebar-container')[0];
        $_sidebarElm.value && $_sidebarElm.value.addEventListener('transitionend', $_sidebarResizeHandler);
    };

    const destroyListener = () => {
        window.removeEventListener('resize', $_resizeHandler.value);
        $_resizeHandler.value = null;

        $_sidebarElm.value && $_sidebarElm.value.removeEventListener('transitionend', $_sidebarResizeHandler);
    };

    onMounted(() => {
        initListener();
    });

    onActivated(() => {
        if (!$_resizeHandler.value) {
            initListener();
        }
        resize();
    });

    onBeforeUnmount(() => {
        destroyListener();
    });

    onDeactivated(() => {
        destroyListener();
    });

    return {
        $_sidebarElm,
        $_resizeHandler
    };
}